package com.altekis.kanbankaze.client;

import java.util.List;

import com.allen_sauer.gwt.dnd.client.PickupDragController;
import com.altekis.kanbankaze.shared.UserAccount;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class AvatarSelectionPresenter {
	interface Display {
		String getAvatarClassName();

		Panel getPanel();
	}

	private PickupDragController avatarDragController;
	protected Display display;
	private final UserAccountServiceAsync userAccountServiceAsync;

	@Inject
	public AvatarSelectionPresenter(
			UserAccountServiceAsync userAccountServiceAsync) {
		this.userAccountServiceAsync = userAccountServiceAsync;
	}

	void bindDisplay(Display display) {
		this.display = display;

		this.avatarDragController = new PickupDragController(RootPanel.get(),
				false);
		this.avatarDragController.setConstrainWidgetToBoundaryPanel(false);
		avatarDragController.setBehaviorDragStartSensitivity(2);
		avatarDragController.setBehaviorMultipleSelection(false);

		userAccountServiceAsync.findAll(new AsyncCallback<List<UserAccount>>() {

			@Override
			public void onSuccess(List<UserAccount> result) {
				showAvatars(result);
			}

			@Override
			public void onFailure(Throwable caught) {
				throw new RuntimeException(caught);
			}
		});
	}

	/**
	 * @param display
	 * @param result
	 */
	private void showAvatars(List<UserAccount> result) {
		for (UserAccount user : result) {
			String url = user.getAvatarUrl();
			Image img = new Image(url);
			img.getElement().setId(user.getId());
			AbsolutePanel absPanel = new AbsolutePanel();
			absPanel.addStyleName(display.getAvatarClassName());
			absPanel.add(img);
			img.addStyleName(display.getAvatarClassName());
			AvatarSelectionPresenter.this.getAvatarDragController()
					.makeDraggable(img);
			display.getPanel().add(absPanel);
		}
	}

	/**
	 * @return the avatarDragController
	 */
	public PickupDragController getAvatarDragController() {
		return avatarDragController;
	}
}
